/**
 * 点击详情按钮，展开右侧面板
 */
import React, { Component } from 'react';
import MoreThanOneOverlay from '../tag/moreThanOneOverlay.jsx';
import { Button } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import Tag from '../tag';
import MdEditor from 'components/mdEditor';
import UILessPluginForCode from 'components/UILessPluginForCode';
import ListEmpty from 'atComponents/ListEmpty';
import ConversationTimeLine from './conversation';
import track from 'utils/track';
import './index.scss';
import intl from '../../../locale';

export default class MoreInfoPanel extends Component {
  state = {
    // 是否展示更多评论
    isShowMore: false,
    // 是否显示整体评论
    isShowWholeCommentMd: false,
  };

  componentDidMount() {
    const detailBottom = document.querySelector('.commit-detail-bottom');
    const panel = document.querySelector('#commit-more-info-panel');
    const top = detailBottom ? detailBottom.getBoundingClientRect().top : 0;
    panel.style.top = `${top > 0 ? top : 0}px`;
  }

  getConversations = () => {
    const { commentList } = this.props;
    const { isShowMore } = this.state;
    // 递归形成讨论块：以无parent_id的评论作为讨论块的跟节点，其子评论平铺在下面
    const conversations = [];
    commentList.forEach((comment) => {
      const isRoot = !comment.parent_id;
      if (isRoot) {
        conversations.push([comment]);
      } else {
        conversations.forEach((conversation) => {
          conversation.forEach((childItem) => {
            if (childItem.id === comment.parent_id) {
              conversation.push(comment);
            }
          });
        });
      }
    });
    let curConversations = [];
    const conversationsLength = conversations.length;
    if (conversationsLength > 8) {
      if (isShowMore) {
        curConversations = conversations.slice(conversationsLength - 8, conversationsLength);
      } else {
        curConversations = conversations;
      }
    } else {
      curConversations = conversations;
    }
    return curConversations;
  };

  showAllCommentArea = () => {
    this.setState({
      isShowWholeCommentMd: true,
    });
  };

  // 提交整体评论或者草稿
  onSubmitWhole = (value, is_draft, parent_id) => {
    const { curCommitInfo } = this.props;

    track({
      action: 'comment',
      page: 'Modal-Commit',
      type: '',
      control: '',
    });

    this.props.postInfo(
      {
        note: value,
        parent_id: parent_id || '',
        sha: curCommitInfo.id,
      },

      () => {
        this.setState({
          isShowWholeCommentMd: false,
        });
      },
    );
  };

  renderCommentList = () => {
    const conversations = this.getConversations();
    return conversations.length ? (
      <div className="commit-comment-info-list">
        {conversations.map((item) => {
          return <ConversationTimeLine data={item} key={item.id} {...this.props} />;
        })}
      </div>
    ) : (
      <ListEmpty
        content={intl.get({
          id: 'code-assets.commitDetail.detail.NoComment',
          defaultMessage: '暂无评论',
        })}
        image="none"
        size="small"
      />
    );
  };

  render() {
    const {
      branches,
      tags,
      changeTags,
      curCommitInfo,
      computebranches,
      computeParentIds,
      commentList,
    } = this.props;
    const { isShowWholeCommentMd, isShowMore } = this.state;
    const parentsLength = curCommitInfo.parent_ids ? curCommitInfo.parent_ids.length : '';
    const moreCommitsLength = commentList.length - 8;
    return (
      <div className="commit-more-info-panel" id="commit-more-info-panel">
        <div className="commit-base-info">
          <div className="base-info-title">
            {intl.get({
              id: 'code-assets.commitDetail.detail.BasicInformation',
              defaultMessage: '基本信息',
            })}
          </div>
          <div className="base-info-type" style={{ display: branches.length ? 'flex' : 'none' }}>
            <div className="type-name">
              {intl.get({ id: 'code-assets.commitDetail.detail.Branch', defaultMessage: '分支' })}
            </div>
            <div className="type-info">
              <MoreThanOneOverlay data={computebranches(branches)} itemType="normal" />
            </div>
          </div>
          <div className="base-info-type" style={{ display: tags.length ? 'flex' : 'none' }}>
            <div className="type-name">
              {intl.get({ id: 'code-assets.commitDetail.detail.Label', defaultMessage: '标签' })}
            </div>
            <div className="type-info">
              <Tag tags={tags} onChange={changeTags} branch={curCommitInfo.id} />
            </div>
          </div>
          {parentsLength ? (
            <div className="base-info-type">
              <div className="type-name">
                {intl.get(
                  {
                    id: 'code-assets.commitDetail.detail.ParentSubmissionParentslength',
                    defaultMessage: '父提交 · {parentsLength}',
                  },
                  { parentsLength },
                )}
              </div>
              <div className="type-info">
                <MoreThanOneOverlay data={computeParentIds(curCommitInfo.parent_ids)} />
              </div>
            </div>
          ) : null}
          <UILessPluginForCode
            identifier="plugin_for_code_commit"
            container={{
              target: 'commit',
              id: curCommitInfo.id,
            }}
          />
        </div>
        <div className="commit-comment-info">
          <div className="comment-info-title">
            {intl.get({
              id: 'code-assets.commitDetail.detail.AllComments',
              defaultMessage: '所有评论',
            })}
          </div>
          <div className="top-switch">
            {commentList.length > 8 ? (
              <div className="show-more-btn">
                <Button
                  type="primary"
                  text
                  onClick={() => {
                    this.setState({
                      isShowMore: !isShowMore,
                    });
                  }}
                >
                  <span style={{ marginRight: '14px' }}>
                    <YunxiaoIcon type="more-line" />
                  </span>
                  <span>
                    {isShowMore
                      ? intl.get(
                          {
                            id: 'code-assets.commitDetail.detail.DisplayEarlierMorecommitslengthComments',
                            defaultMessage: '显示较早的{moreCommitsLength}条评论',
                          },
                          { moreCommitsLength },
                        )
                      : intl.get({
                          id: 'code-assets.commitDetail.detail.HideEarlierComments',
                          defaultMessage: '隐藏较早的评论',
                        })}
                  </span>
                </Button>
              </div>
            ) : null}
          </div>
          {this.renderCommentList()}
        </div>
        <div
          className={`commit-comment-bottom-wrapper height-transition ${
            isShowWholeCommentMd ? 'h190' : 'h61'
          }`}
        >
          <div
            className="text"
            onClick={this.showAllCommentArea}
            style={{ display: isShowWholeCommentMd ? 'none' : 'block' }}
          >
            {intl.get({
              id: 'code-assets.commitDetail.detail.EnterAComment',
              defaultMessage: '请输入评论',
            })}
          </div>
          {isShowWholeCommentMd ? (
            <div className="md">
              {/* 整体评论的md编辑器 */}
              <MdEditor
                initValue={''}
                onSubmitImmediate={this.onSubmitWhole}
                // onSubmit={this.onSubmitWhole}
                btnAlign="left"
                onCancel={() => {
                  this.setState({
                    isShowWholeCommentMd: false,
                  });
                }}
                useInLog
                // submitBtnText={'保存为草稿'}
              />
            </div>
          ) : null}
        </div>
      </div>
    );
  }
}
